// Common file dialog support
#include <windows.h>
#include "filedlg.h"

void fileInitCallerStruct(LPOPENFILENAME ofn, PFILECALLER caller, ULONG flags)
{
	memset(ofn,0,sizeof(OPENFILENAME));
	ofn->lStructSize = sizeof(OPENFILENAME);
	ofn->Flags = flags;
	ofn->nMaxFile = MAX_FILENAME_LENGHT;
	ofn->lpstrFile = (char *)malloc(MAX_FILENAME_LENGHT);
	ofn->hwndOwner = caller->hwndOwner;
	ofn->lpstrFile[0]='\0';
	ofn->lpstrFilter = caller->filter;
	ofn->lpstrInitialDir = caller->directory;
	if (caller->name)
		strcpy(ofn->lpstrFile, caller->name);
}

char *fileRequestFileNameAndFree(LPOPENFILENAME ofn, char *fileName, int ret)
{
	if (ret)
	{
		if (fileName)
			strcpy(fileName, ofn->lpstrFile);
		else
			fileName = strdup(ofn->lpstrFile);
		// Update the working directory
		if (ofn->lpstrInitialDir){
			GetCurrentDirectory(300, (char*)ofn->lpstrInitialDir);
		}
	}
	else
		fileName = NULL;
	free(ofn->lpstrFile);
	return fileName;
}

char *fileSaveFile(PFILECALLER caller, char *fileName)
{
	OPENFILENAME ofn;
	int ret = 0;
	
	fileInitCallerStruct(&ofn, caller, OFN_OVERWRITEPROMPT);

	ret = GetSaveFileName(&ofn);

	return fileRequestFileNameAndFree(&ofn, fileName, ret);
}

char *fileLoadFile(PFILECALLER caller, char *fileName)
{
	OPENFILENAME ofn;
	int ret = 0;
		
	fileInitCallerStruct(&ofn, caller, OFN_FILEMUSTEXIST);

	ret = GetOpenFileName(&ofn);

	return fileRequestFileNameAndFree(&ofn, fileName, ret);
}
